package com.bigmodel.config.websocket;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bigmodel.taskmanager.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket操作类
 *
 * @author zxx
 * @date 2022-08-22 10:00
 * @since 1.0.0
 */
@Component
@Slf4j
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {


    // 当前用户id
    private String userId;
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //新：使用map对象优化，便于根据sid来获取对应的WebSocket
    //虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
    private static ConcurrentHashMap<String, WebSocketServer> websocketMap = new ConcurrentHashMap<>();

    // 用来存在线连接数
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            this.userId = userId;
            websocketMap.put(userId, this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接，总数为:" + websocketMap.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            if (websocketMap.containsKey(this.userId)) {
                websocketMap.remove(this.userId);
                sessionPool.remove(this.userId);
            }
            log.info("【websocket消息】连接断开，总数为:" + websocketMap.size());
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端消息:" + message);
        // 调用自己的业务逻辑（此处可自行更换）

        /*Map<String,String> answerFirst = new HashMap<>();
        answerFirst.put("userId",userId);
        answerFirst.put("blockId", UUID.fastUUID().toString().replaceAll("-",""));
        answerFirst.put("answerContent","处理中,请稍候....");
        sendOneMessage(userId,JSONUtil.toJsonStr(answerFirst));*/

        String answerContent = "";

        try {
                JSONObject jsonObject = JSONUtil.parseObj(message);
                TaskService taskService = new TaskService();
                answerContent = taskService.receiveQuestion(jsonObject.getStr("questionContent"));
        }catch (Exception e){
            e.printStackTrace();
            answerContent = "sorry,处理失败请再次尝试";
        }

        String answerBlockId = UUID.fastUUID().toString().replaceAll("-","");
        for(int i = 0 ; i<answerContent.length(); i++) {
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Map<String, String> answer = new HashMap<>();
            answer.put("userId", userId);
            answer.put("answerContent", String.valueOf(answerContent.charAt(i)));
            answer.put("blockId", answerBlockId);
            sendOneMessage(userId, JSONUtil.toJsonStr(answer));
        }

    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误,原因:" + error.getMessage());
        error.printStackTrace();
    }


    // 此为广播消息
    public void sendAllMessage(String message) {
        log.info("【websocket消息】广播消息:" + message);

        for (Map.Entry<String, WebSocketServer> map : websocketMap.entrySet()) {
            WebSocketServer webSocketServer = map.getValue();
            if (webSocketServer.session.isOpen()) {
                webSocketServer.session.getAsyncRemote().sendText(message);
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                log.info("【websocket消息】单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
